#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        vector<int> row(m + 1, 0);
        vector<int> col(m + 1, 0);
        vector<vector<int>> squsize(n + 1, vector<int>(m + 1, 0));
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                if (matrix[i - 1][j - 1] == '1')
                {
                    row[j] = row[j - 1] + 1;
                    squsize[i][j] = min(squsize[i - 1][j - 1], min(row[j - 1], col[j])) + 1;
                    col[j] = col[j] + 1;
                }
                else
                {
                    row[j] = 0;
                    col[j] = 0;
                    squsize[i][j] = 0;
                }
            }
        }
        int res = 0;
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                res = max(res, squsize[i][j]);
            }
        }
        return res * res;
    }
};